﻿Imports System.Windows.Media.Imaging
Imports System.Reflection
Imports System.Globalization
Imports System.IO

Namespace ViewModel

    Public Class StationViewModel
        Inherits ViewModelBase

        Private StationModel As Model.StationModel
        Public Sub New(ByVal model As Model.StationModel)
            StationModel = model
        End Sub

        Private _isChanged As Boolean
        Public Property IsChanged() As Boolean
            Get
                Return _isChanged
            End Get
            Set(ByVal value As Boolean)
                _isChanged = value
            End Set
        End Property

        Public ReadOnly Property Kind() As StationKind
            Get
                If Me.Id.StartsWith("ch", StringComparison.InvariantCulture) Then
                    Return StationKind.Channel
                ElseIf Me.Id.StartsWith("co", StringComparison.InvariantCulture) Then
                    Return StationKind.Community
                Else
                    Return StationKind.None
                End If
            End Get
        End Property

        Public ReadOnly Property Id() As String
            Get
                Return StationModel.Id
            End Get
        End Property

        Public Property Name() As String
            Get
                Return StationModel.Name
            End Get
            Set(ByVal value As String)
                StationModel.Name = value
                OnPropertyChanged("Name")
            End Set
        End Property

        Private _rating As Integer
        Public Property Rating() As Integer
            Get
                Return _rating
            End Get
            Set(ByVal value As Integer)
                If value < 0 Then
                    _rating = 0
                ElseIf value > 5 Then
                    _rating = 5
                Else
                    _rating = value
                End If
                IsChanged = True
                OnPropertyChanged("Rating")
            End Set
        End Property

        Private _isAlertTarget As Boolean
        Public Property IsAlertTarget() As Boolean
            Get
                Return _isAlertTarget
            End Get
            Set(ByVal value As Boolean)
                _isAlertTarget = value
                IsChanged = True
                OnPropertyChanged("IsAlertTarget")

                _alertSettings.IsEnabled = IsAlertTarget
                OnPropertyChanged("AlertSettings")
            End Set
        End Property

        Private _alertSettings As New AlertSettingsViewModel
        Public Property AlertSettings() As AlertSettingsViewModel
            Get
                Return _alertSettings
            End Get
            Set(ByVal value As AlertSettingsViewModel)
                IsChanged = True
                _alertSettings = value
                OnPropertyChanged("AlertSettings")
            End Set
        End Property

        Public ReadOnly Property Uri() As Uri
            Get
                Select Case Me.Kind
                    Case StationKind.Channel
                        Return New Uri(String.Format(CultureInfo.InvariantCulture, My.Settings.ChannelUriFormat, Me.Id))
                    Case Else ' StationType.Community
                        Return New Uri(String.Format(CultureInfo.InvariantCulture, My.Settings.CommunityUriFormat, Me.Id))
                End Select
            End Get
        End Property

#Region "Icon"
        Private Shared _cachePath As String = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly.Location)
        Public Shared Property CachePath() As String
            Get
                Return _cachePath
            End Get
            Set(ByVal value As String)
                'Try
                '    My.Computer.FileSystem.CreateDirectory(value)
                'Catch ex As IOException
                '    Exit Property
                'End Try
                _cachePath = value
            End Set
        End Property

        Private ReadOnly Property CachedIconPath() As String
            Get
                Return System.IO.Path.Combine(StationViewModel.CachePath, Me.Id & ".jpg")
            End Get
        End Property

        Private WithEvents WebClient As System.Net.WebClient

        Private ReadOnly Property CachedIcon() As BitmapImage
            Get
                Dim icon As BitmapImage = Nothing
                If System.IO.File.Exists(Me.CachedIconPath) Then
                    Dim info = New System.IO.FileInfo(Me.CachedIconPath)

                    Try
                        icon = New BitmapImage(New Uri(Me.CachedIconPath))

                        ' 更新
                        If info.LastWriteTime.AddHours(3) < Now Then
                            DownloadIconAsync()
                        End If

                    Catch fileNotFoundEx As System.IO.FileNotFoundException
                        ' Ignore
                    Catch ex As Exception
                        ' Ignore
                    End Try
                Else
                    DownloadIconAsync()
                End If

                If icon Is Nothing Then
                    Return StationViewModel.NoImageIcon
                Else
                    Return icon
                End If
            End Get
        End Property

        Private Sub DownloadIconAsync()
            Dim uri As Uri
            Select Case Me.Kind
                Case StationKind.Channel
                    uri = New Uri(String.Format(CultureInfo.InvariantCulture, My.Settings.ChannelIconUriFormat, Me.Id))
                Case Else ' StationType.Community
                    uri = New Uri(String.Format(CultureInfo.InvariantCulture, My.Settings.CommunityIconUriFormat, Me.Id))
            End Select

            WebClient = New System.Net.WebClient
            WebClient.DownloadFileAsync(uri, Me.CachedIconPath)
        End Sub

        Private _icon As BitmapImage
        Public ReadOnly Property Icon() As ImageSource
            Get
                If _icon Is Nothing Then
                    _icon = Me.CachedIcon
                End If
                Return _icon
            End Get
        End Property

        Private Shared _noImageIcoon As BitmapImage
        Private Shared ReadOnly Property NoImageIcon() As BitmapImage
            Get
                If _noImageIcoon Is Nothing Then
                    Dim noimageUri = New Uri("pack://application:,,,/NamaAlert;component/noimage.jpg")
                    _noImageIcoon = New BitmapImage(noimageUri)
                End If
                Return _noImageIcoon
            End Get
        End Property

        Private Sub WebClient_DownloadFileCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) Handles WebClient.DownloadFileCompleted

            WebClient.Dispose()
            WebClient = Nothing

            If e.Cancelled Then
                Exit Sub
            End If

            Try
                If System.IO.File.Exists(Me.CachedIconPath) Then
                    Dim info = New System.IO.FileInfo(Me.CachedIconPath)
                    If info.Length = 0 Then

                        Try
                            System.IO.File.Delete(Me.CachedIconPath)

                        Catch dirEx As DirectoryNotFoundException
                            ' Ignore
                        Catch ioEx As IOException
                            ' Ignore
                        Catch unauthEx As UnauthorizedAccessException
                            ' Ignore
                        End Try

                    Else
                        Try
                            _icon = New BitmapImage(New Uri(Me.CachedIconPath))
                            OnPropertyChanged("Icon")
                        Catch fileNotFoundEx As System.IO.FileNotFoundException
                            ' Ignore
                        Catch ex As Exception
                            ' Ignore
                        End Try
                    End If
                End If

            Catch ex As Exception
#If DEBUG Then
                Stop
#End If
            End Try

        End Sub

        Protected Overrides Sub OnDispose()
            Try
                If WebClient IsNot Nothing Then
                    If WebClient.IsBusy Then
                        WebClient.CancelAsync()
                    End If
                    WebClient.Dispose()
                End If
            Catch ex As Exception
                ' Ignore
            End Try
            MyBase.OnDispose()
        End Sub

#End Region

    End Class

End Namespace